<!-- 接口不太对，是要加上一个展示所有课程的表，等接口补充完整 -->
<template>
    <el-card>
<div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 20px;">
      <el-breadcrumb-item :to="{ path: '/teacherHome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>学生管理</el-breadcrumb-item>
      <el-breadcrumb-item>开设课程</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <!-- Add your course-related form items here -->
      <el-form-item label="课程ID" prop="courseId">
        <el-input v-model="ruleForm.courseId"></el-input>
      </el-form-item>
      <!-- Remove the previous student-related form items -->
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">立即开设</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
      <!-- 课程表格 -->
      <el-table
          :data="tableData"
          border
          style="width: 100%">
        <el-table-column
            fixed
            prop="name"
            label="课程名称"
            width="200">
        </el-table-column>
        <el-table-column
            prop="courseId"
            label="课程ID"
            width="150">
        </el-table-column>
        <el-table-column
            prop="credit"
            label="学分"
            width="150">
        </el-table-column>
        <el-table-column
            prop="period"
            label="时间"
            width="150">
        </el-table-column>
        <el-table-column
            prop="collegeId"
            label="学院号"
            width="150">
        </el-table-column>
        <el-table-column
            label="操作"
            width="100">
          <template slot-scope="scope">
            <el-popconfirm
                confirm-button-text='确认开设'
                cancel-button-text='取消'
                icon="el-icon-info"
                title="确定开设这门课程？"
                @confirm="handleInsert(scope.row)"
            >
              <el-button slot="reference" type="primary" size="small">开设</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
          <el-pagination
        :page-sizes="[1, 2, 5]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :total="firstFrom.total">
      </el-pagination>
    </el-form>
  </div>
</el-card>
</template>

<script>
export default {
  name: "InsertCourseInfo",
data() {
  return {
    title: "开设课程",
    ruleForm: { courseId: ''},
    rules: {
      courseId: [
        { required: true, message: "请填写课程ID" },
        // Add any additional validation rules for courseId if needed
      ],
    },
    tableData: [
],
      firstFrom:{
        // 用于保存初始的条数
      total:0,
      },
    pageFrom:{
      page: 1,
      pageSize: 2,
      id:'',
      // 要传给后端的数据
      },
      courseName:'',
      courseId:'',
  };
},
created() {
     // 初始化操作
     if(localStorage.getItem("type") !== 'teacher'){this.$router.push(`/login`);this.$message.error('你不是老师');}
    this.name = localStorage.getItem('name');
    this.pageFrom.id = localStorage.getItem('teacherId');
    this.getOwnFirstCourse();
  },
methods: {
    // 开设课程信息
async insertCourseInfo(ID) {
  const dataToSerialize = {};
      if (ID) {
    dataToSerialize.courseId=ID;
}

        if (this.pageFrom.id) {
      dataToSerialize.teacherId=this.pageFrom.id;
}
    // JSON化
    const config = {
      headers: {
          'Content-Type': 'application/json',
          'token':`${localStorage.getItem("token")}`// Custom request header
        }
      };
    try {
      const { data: res } = await this.$http.post('api/teacher/course/insert',JSON.stringify(dataToSerialize), config)
      if (res.status !== 500) {
        this.$message.success('成功开设该门课程');
        // 重新调用获取表格的代码
        this.getOwnFirstCourse();
      } else {
        this.$message.error('开设失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('开设失败');
  }
    },

handleCurrentChange(currentPage) {
      this.pageFrom.page = currentPage;
      // 每次更改都要请求一次tabledata数据，在后端做数据分页！>.<
      this.getOwnCourse();

    },
handleSizeChange(size) {
      this.pageFrom.pageSize = size;
      // 每次更改都要请求一次tabledata数据，在后端做数据分页！>.<！
       this.getOwnCourse()
    },
async getOwnCourse() {
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`// Custom request header
      }
    };
    try {
      const { data: res } = await this.$http.post(`api/course/page`,JSON.stringify(this.pageFrom),config);
      if (res.status !== 500) {
        this.tableData=res.data.records;
      } else {
        this.$message.error('获取失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('请求失败');
  }
},  
// 获取所有数据并保存
async getOwnFirstCourse() {
    // JSON化
    this.pageFrom.pageSize=10
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`// Custom request header
      }
    };
    try {
      const { data: res } = await this.$http.post(`api/course/page`,JSON.stringify(this.pageFrom),config);
      if (res.status !== 500) {
        this.$message.success('成功获取课程列表');
        this.tableData=res.data.records;
        this.firstFrom.total = res.data.total; // 保存总条数

      } else {
        this.$message.error('出错了，请联系管理员');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('你还没有开设课程');
  }
},

handleInsert(row){
  this.insertCourseInfo(row.courseId);
},
// 提交表单信息
submitForm(ruleForm) {
  this.$refs[ruleForm].validate((valid) => {
    if (valid) {
      this.insertCourseInfo(this.ruleForm.courseId);
    } else {
      this.$message.error('请将信息填写完整');
    }
  });
},

// 重置清空表单信息
resetForm(formName) {
  this.$refs[formName].resetFields();
},

}}
</script>

<style lang="less" scoped>
.el-breadcrumb {
  padding-bottom: 10px;
}
.el-input {
  width: 40%;
}
/deep/ .el-textarea__inner {
  width: 40%;
  line-height: 3;
}
.el-form-item {
  margin: 18px 0 !important;
}
</style>